<template>
  <el-card class="course-card">
    <img  @click="router.push('/detail/'+resource.resourceId)" :src="baseURL+'resource/download/'+resource.imgPath" class="course-cover" />
    <div class="course-info">
      <h3>{{ resource.title.length > 16 ? resource.title.substring(0, 16)+'...': resource.title }}</h3>
      <p>{{ resource.description.length > 10 ? resource.description.substring(0, 10)+'...': resource.description }}</p>
      <div class="course-meta">
        <span>{{ cache.get('user/',resource?.authorId)?.username }}</span>
        <span>{{ cache.get('category/get/',resource.categoryId)?.categoryName }}</span>
      </div>
      <div class="course-actions">
        <el-rate disabled :max="5" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" allow-half v-model="rating"></el-rate>
<!--        <el-button type="primary" plain>查看详情</el-button>-->
        <el-button :icon="hasCollection?StarFilled:Star" circle @click="toggleFavorite(resource.resourceId)" />
      </div>
    </div>
  </el-card>
</template>
<script setup>
import {Star, StarFilled} from "@element-plus/icons-vue";
import {computed, defineProps} from 'vue'
import {useStore} from "vuex";
import api from "@/api/index.js";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import cache from '@/utils/cacheGetter.js'

const router = useRouter()
const props = defineProps({
  resource:{type:Object,default:{resourceId:0,imgPath:'',title:'无',description:'无',authorId:'未知',categoryId:'类型'}}
})
const rating = computed(
    {
        get() {
            return cache.get('userRating/resource',props.resource.resourceId)?.ratingScore
        },
        set(newValue) {

        }
    }
)

const baseURL = api.getInstance().defaults.baseURL
const hasCollection = computed(
    {
        get() {
            return cache.get('userCollection/user',props.resource.resourceId)
        },
        set(newValue) {

        }
    }
)
const toggleFavorite = (id)=>{
  if (hasCollection.value) {
    api.delete('userCollection/user/delete/' + id).then(resp=>{
      ElMessage.success('取消收藏成功')
      cache.flush('userCollection/user',id)
    })
  } else {
    api.post('userCollection/user/add/'+id).then(resp=>{
      ElMessage.success('收藏成功')
      cache.flush('userCollection/user',id)
    })
  }
}
cache.flush('userCollection/user',props.resource.resourceId)
</script>
<style scoped>
.course-card {
  height: 400px;
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.course-card:hover {
  transform: translateY(-5px);
}

.course-cover {
  width: 100%;
  height: 180px;
  object-fit: cover;
}


.course-meta {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 12px;
  margin-bottom: 15px;
}

.course-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-info {
  padding: 10px;
}
</style>